import logging
import signal
import sys
from concurrent import futures
from pathlib import Path

import grpc
import typer

from parnassus.protos.arm_stream import arm_stream_pb2_grpc
from parnassus.servers.arm_stream.servicer import ArmEnvServicer

app = typer.Typer(help="gRPC server for ArmEnv streaming service")


@app.command()
def serve(
    port: int = typer.Option(50051, help="Port to listen on"),
    max_workers: int = typer.Option(10, help="Maximum number of worker threads"),
    log_level: str = typer.Option("INFO", help="Logging level"),
):
    """启动 gRPC 服务器"""
    logging.basicConfig(
        level=getattr(logging, log_level.upper()),
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )

    server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))

    # 添加服务
    servicer = ArmEnvServicer()
    arm_stream_pb2_grpc.add_ArmEnvServicer_to_server(servicer, server)

    # 监听端口
    listen_addr = f"[::]:{port}"
    server.add_insecure_port(listen_addr)

    # 启动服务器
    server.start()
    logging.info(f"ArmEnv gRPC server started on {listen_addr}")

    # 优雅关闭处理
    def signal_handler(signum, frame):
        logging.info("Received shutdown signal")
        server.stop(grace=5)
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    try:
        server.wait_for_termination()
    except KeyboardInterrupt:
        logging.info("Server interrupted")
    finally:
        server.stop(grace=5)

    logging.info(f"Starting ArmEnv gRPC server with config:")
    logging.info(f"  Port: {port}")
    logging.info(f"  Max workers: {max_workers}")
    logging.info(f"  Log level: {log_level}")

@app.command()
def dummy():
    """一个占位命令，防止 Typer 报错"""
    pass

def main():
    app()


if __name__ == "__main__":
    main()
